<template>
	<div class="pdf-viewer-wrap">
		<div id="pdfjs-container" class="page-container">
			<div id="pdfViewer" class="pdfViewer"></div>
		</div>
	</div>
</template>
<script setup lang="ts">
import 'pdfjs-dist/legacy/web/pdf_viewer.css'
import * as pdfjsLib from 'pdfjs-dist/legacy/build/pdf.js' // 这一这个和新浏览器的不同
import * as pdfjsViewer from 'pdfjs-dist/legacy/web/pdf_viewer'
import 'pdfjs-dist/legacy/build/pdf.worker.entry'
import * as pdfjsSandbox from 'pdfjs-dist/legacy/build/pdf.sandbox.js'
import { PDFDocumentProxy } from 'pdfjs-dist/types/src/display/api'

const SANDBOX_BUNDLE_SRC = pdfjsSandbox

pdfjsLib.GlobalWorkerOptions.workerSrc = window.pdfjsWorker

const CMAP_URL = '/pdfjs-dist/cmaps/'
const CMAP_PACKED = true
const STANDARD_FONT_DATA_URL = '/pdfjs-dist/standard_fonts/'

window.pdfjsLib = pdfjsLib
window.pdfjsViewer = pdfjsViewer

const pdfEventBus = new pdfjsViewer.EventBus()

const pdfScriptingManager = new pdfjsViewer.PDFScriptingManager({
	eventBus: pdfEventBus,
	sandboxBundleSrc: SANDBOX_BUNDLE_SRC,
})
const pdfLinkService = new pdfjsViewer.PDFLinkService({
	eventBus: pdfEventBus,
})

var pdfViewer: pdfjsViewer.PDFViewer | null = null
var pdfDocument: PDFDocumentProxy | null = null

const pdfUrl = '/test.pdf'
async function initPage() {
	if (!pdfUrl) return
	var container = document.getElementById(`pdfjs-container`)
	pdfDocument = await pdfjsLib.getDocument({
		url: pdfUrl as unknown as URL,
		cMapUrl: CMAP_URL,
		cMapPacked: CMAP_PACKED,
		standardFontDataUrl: STANDARD_FONT_DATA_URL,
	}).promise
	pdfViewer = new pdfjsViewer.PDFViewer({
		container: container as unknown as HTMLDivElement,
		eventBus: pdfEventBus,
		annotationMode: 0,
		annotationEditorMode: 0,
		scriptingManager: pdfScriptingManager,
		linkService: pdfLinkService,
	})

	pdfScriptingManager.setDocument(pdfDocument)
	pdfScriptingManager.setViewer(pdfViewer)
	pdfLinkService.setDocument(pdfDocument)
	pdfLinkService.setViewer(pdfViewer)

	pdfViewer.setDocument(pdfDocument)

	pdfEventBus.on('pagesinit', () => {
		if (pdfViewer) {
			console.log('init')
		}
	})
}

onMounted(async () => {
	initPage()
})
</script>
<style lang="scss" scoped>
.pdf-viewer-wrap {
	#pdfjs-container {
		position: absolute; // 必须要绝对定位
		left: 100px;
		top: 100px;
		width: 800px;
		height: 800px;
		overflow: auto;
		border: 2px solid red;
	}
}
</style>
